#include "threeSumClosest.h"
int threeSumClosest(std::vector<int> &nums, int target) {
    std::sort(nums.begin(), nums.end());
    const int n = nums.size();
    int left = 0, right = 0, sumValue = 0, distant = 0;
    int result = std::numeric_limits<int>::max();
    int minTarget = std::numeric_limits<int>::max();
    for (int i = 0; i <= n - 3; i++) {
        left = i + 1;
        right = n - 1;
        while (left < right) {
            sumValue = nums[left] + nums[right] + nums[i];
            distant = std::abs(sumValue - target);
            if (distant < minTarget) {
                minTarget = distant;
                result = sumValue;
            }
            if (sumValue < target) {
                left++;
            } else {
                right--;
            }
        }
    }
    return result;
}
